package com.diy.ibatis.Sqlsession;

import com.diy.ibatis.cfg.Configuration;
import com.diy.ibatis.utils.DataSourceUtil;

import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * Sqlsession接口的实现
 *
 */
public class Sqlsessionimpl implements SqlSession {

    private Configuration cfg;
    private Connection conn;
    public Sqlsessionimpl(Configuration cfg){
        this.cfg=cfg;
       conn= DataSourceUtil.getConnection(cfg);
    }
    /**
     * 用于创建代理对象
     * @param daointerfacleClass
     * @param <T>
     * @return
     */
    public <T> T getMapper(Class<T> daointerfacleClass) {
        return(T) Proxy.newProxyInstance(daointerfacleClass.getClassLoader(),new Class[]{daointerfacleClass},new MapperProxy(cfg.getMappers(),conn));

    }

    /**
     * 用于释放资源
     */
    public void close() {
        if(conn != null){
        try {
            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    }
}
